from git_repository_factory import GitRepositoryFactory
from utils.common_utils import write_json,get_project_folders
from utils.conversion_data import *
import os
import json
from tqdm import tqdm
import time

if __name__ == '__main__':
    # 获取当前文件的绝对路径
    file_name = os.path.abspath(__file__)
    # 获取当前文件所在的目录
    parent_dir = os.path.dirname(file_name)
    # 获取父级目录中的某个特定文件夹中的 JSON 文件路径
    json_file_path = os.path.join(parent_dir, 'config', 'config.json')
    config = None
    # 读取 JSON 文件内容
    try:
        with open(json_file_path, 'r', encoding='utf-8') as file:
            config = json.load(file)
    except FileNotFoundError:
        print(f'Error: The file {json_file_path} does not exist.')
    except json.JSONDecodeError as e:
        print(f'Error parsing the JSON file: {e}')
    except Exception as e:
        print(f'An unexpected error occurred: {e}')
    targetDir = config["RESOURCES_DIR"]
    js_output_path = config["EXTRACT_FUNCTIONS_CACHE_DIR"]
    result_path = config["OUTPUT_DIR"]

    # 遍历待处理的目标文件夹下的所有子文件夹，他们都是NPM三方库
    project_folders =get_project_folders(targetDir)

    total_projects = len(project_folders)
    # 创建进度条
    with tqdm(total=1, desc="Processing projects", unit="project") as pbar:
        for project_folder in project_folders:
            # 处理项目
            project_folder = r"D:\Project\testDir\testLibs\adadomains-sdk"
            p = GitRepositoryFactory.parser_js_git_repository(r"D:\Project\testDir\testLibs\react-native")
            p.js_output_path = js_output_path
            # 没有版本发布记录就仅保存当前的版本记录
            diff_function_info = []
            version_diff_function_mate_info = []
            version_mate_info = []
            if len(p.tags) == 0:
                history_no_diff_functions = p.analysis_functions_info(r"D:\Project\testDir\testLibs\react-native")
                history_no_diff_functions = converion_history(history_no_diff_functions)
            else:
                p.js_output_path = config["EXTRACT_FUNCTIONS_CACHE_DIR"]
                modified_function = p.analysis_all_version_modified_function()
                history_no_diff_functions = converion_history(p.history_no_diff_functions)
                (version_mate_info, version_diff_function_mate_info,
                 diff_function_info) = conversion_data(p, modified_function)
                generate_version_in_function_diff_info(version_mate_info,version_diff_function_mate_info,diff_function_info)
                if not diff_function_info:
                    raise ValueError(f"No diff_function_info generated for {project_folder}")
            if not diff_function_info:
                library_name = os.path.basename(project_folder)
            else:
                library_name = diff_function_info[0].get("library", os.path.basename(project_folder))
            library_dir = os.path.join(config["OUTPUT_DIR"], library_name)
            os.makedirs(library_dir, exist_ok=True)
            # 写入JSON文件 - 与原版本一致
            write_json(history_no_diff_functions, os.path.join(library_dir, "history_no_diff_function.json"))
            if  diff_function_info:
                write_json(version_diff_function_mate_info, os.path.join(library_dir, "version_diff_function_mate.json"))
                write_json(diff_function_info, os.path.join(library_dir, "diff_function_info.json"))
                write_json(version_mate_info, os.path.join(library_dir, "version_mate_info.json"))

            p.reset_init_commit()

            # 更新进度条
            pbar.update(1)
            pbar.set_postfix(last_update=time.strftime("%H:%M:%S"))



